package com.ibeeking.found.open.b.rest.service.impl;

import com.dingtalk.service.DingTalkService;
import com.dingtalk.service.impl.DingTalkServiceImpl;
import com.ibeeking.found.common.constants.WxCpServiceTypeConstant;
import com.ibeeking.found.common.entity.open.*;
import com.ibeeking.found.common.enums.AliDingTalkAppTypeEnum;
import com.ibeeking.found.common.enums.OpenApiConfigEnum;
import com.ibeeking.found.common.enums.WxCpAppTypeEnum;
import com.ibeeking.found.common.enums.WxOpenAppTypeEnum;
import com.ibeeking.found.common.response.ResponseCodeEnum;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.gmc.global.api.feign.GlobalOpenFeignClient;
import com.ibeeking.found.open.b.rest.config.prop.FileConfigProp;
import com.ibeeking.found.open.b.rest.config.prop.RedisProperties;
import com.ibeeking.found.open.b.rest.service.IOpenService;
import com.ibeeking.found.open.service.common.constants.RedisKeyConstant;
import com.ibeeking.nematos.core.utils.SpringBeanUtil;
import com.ibeeking.nematos.exception.BusinessException;
import com.ibeeking.nematos.exception.DataNotExistException;
import com.ibeeking.nematos.redis.utils.RedisUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import me.chanjar.weixin.common.bean.WxAccessToken;
import me.chanjar.weixin.common.redis.JedisWxRedisOps;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.config.WxCpTpConfigStorage;
import me.chanjar.weixin.cp.config.impl.WxCpTpRedissonConfigImpl;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;
import me.chanjar.weixin.cp.tp.service.impl.WxCpTpServiceImpl;
import me.chanjar.weixin.open.api.WxOpenComponentService;
import me.chanjar.weixin.open.api.WxOpenMaService;
import me.chanjar.weixin.open.api.WxOpenMpService;
import me.chanjar.weixin.open.api.WxOpenService;
import me.chanjar.weixin.open.api.impl.WxOpenInRedisConfigStorage;
import me.chanjar.weixin.open.bean.WxOpenAuthorizerAccessToken;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 禁止在此类加其他业务方法
 *
 * @ClassName WxMpService
 * @Description
 * @Author ibeeking
 * @Date 2020-12-30 10:29
 **/
@Service
@EnableConfigurationProperties({RedisProperties.class})
public class OpenServiceImpl implements IOpenService {
    private Logger logger = LoggerFactory.getLogger(getClass());
    //30分钟
    private static final Long TIME = 30 * 60 *1000L;

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private FileConfigProp fileConfigProp;

    @Autowired
    private RedisProperties redisProperties;

    @Resource
    private GlobalOpenFeignClient globalOpenFeignClient;

    private OpenConfigDTO queryOpenConfig(Integer type, Integer subType) {
        OpenConfigQuery query = new OpenConfigQuery();
        query.setType(type);
        query.setSubType(subType);
        ResponseResult<OpenConfigDTO> responseResult = globalOpenFeignClient.queryOpenConfigOne(query);
        OpenConfigDTO openConfigDTO = responseResult.getData();
        return openConfigDTO;
    }

    private OpenAuthDTO queryOpenAuthByTenantIdAndType(Long tenantId, Integer appType){
        OpenAuthQuery query = new OpenAuthQuery();
        query.setTenantId(tenantId);
        query.setAppType(appType);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        return responseResult.getData();
    }

    private OpenAuthDTO queryOpenAuthByOpenAppIdAndType(String openAppId, Integer appType){
        OpenAuthQuery query = new OpenAuthQuery();
        query.setOpenAppId(openAppId);
        query.setAppType(appType);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        return responseResult.getData();
    }

    private OpenAuthDTO queryOpenAuthByComponentAppIdAndAppId(String componentAPPId, String appId){
        OpenAuthQuery query = new OpenAuthQuery();
        query.setComponentAppId(componentAPPId);
        query.setAppId(appId);
        ResponseResult<OpenAuthDTO> responseResult = globalOpenFeignClient.queryOpenAuthOne(query);
        return responseResult.getData();
    }

    @Override
    public  OpenConfigDTO queryWxOpenConfigByComponentAppId(String componentAppId){
        OpenConfigQuery query = new OpenConfigQuery();
        query.setComponentAppId(componentAppId);
        query.setType(OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_OPEN.getCode());
        query.setSubType(WxOpenAppTypeEnum.WECHAT_OPEN_APP_TYPE_TP.getCode());
        ResponseResult<OpenConfigDTO> responseResult = globalOpenFeignClient.queryOpenConfigOne(query);
        DataUtils.trueThrowException(!ResponseCodeEnum.SUCCESS.getCode().equals(responseResult.getCode()), responseResult.getMsg());
        return responseResult.getData();
    }
    /**
     * 获取开放平台服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxOpenService getDefaultWxOpenService() {
        WxOpenService wxOpenService = SpringBeanUtil.getBean(WxOpenService.class);
        if(wxOpenService == null) throw new BusinessException("get WxOpenService service error!");
        return wxOpenService;
    }
    /**
     * 获取开放平台服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxOpenService getWxOpenService(String componentAppId) {
        WxOpenService wxOpenService = SpringBeanUtil.getBean(WxOpenService.class);
        if(wxOpenService == null) throw new BusinessException("get WxOpenService service error!");
        WxOpenInRedisConfigStorage redisConfigStorage = null;
        String key = RedisKeyConstant.WX_OPEN_CONFIG_KEY.concat(componentAppId);
        Object objConfigStorage = redisUtils.get(key);
        if(ObjectUtils.isEmpty(objConfigStorage)) {
            OpenConfigDTO wxOpenConfig = queryWxOpenConfigByComponentAppId(componentAppId);
            if(wxOpenConfig == null) throw new BusinessException("没有读取到开放平台配置参数!");
            OpenConfigOfExtend openConfigOfExtend = wxOpenConfig.getOpenConfigOfExtend();
            redisConfigStorage = new WxOpenInRedisConfigStorage(redisProperties.getJedisPool(), "wx:open");
            redisConfigStorage.setComponentAppId(wxOpenConfig.getComponentAppId());
            redisConfigStorage.setComponentAppSecret(wxOpenConfig.getOpenAppSecret());
            redisConfigStorage.setComponentToken(wxOpenConfig.getComponentMsgToken());
            redisConfigStorage.setComponentAesKey(wxOpenConfig.getComponentMsgAesKey());
            if(openConfigOfExtend != null) {
                OpenConfigOfWxOpen openConfigOfWxOpen = openConfigOfExtend.getOpenConfigOfWxOpen();
                if (openConfigOfWxOpen != null) {
                    redisConfigStorage.setComponentVerifyTicket(openConfigOfWxOpen.getComponentVerifyTicket());
                    redisConfigStorage.setComponentAccessToken(openConfigOfWxOpen.getComponentAccessToken());
                }
            }
            wxOpenService.setWxOpenConfigStorage(redisConfigStorage);
            redisUtils.set(key, redisConfigStorage, 1000);
         }else{
            redisConfigStorage = (WxOpenInRedisConfigStorage) objConfigStorage;
            wxOpenService.setWxOpenConfigStorage(redisConfigStorage);
         }
        return wxOpenService;
    }
    /**
     * 获取公众号服务并将注册为bean
     *
     * @param appId
     * @return
     */
    @Override
    public WxOpenMpService getWxOpenMpService(String componentAppId, String appId) {
        WxOpenService wxOpenService = getBean().getWxOpenService(componentAppId);
        if (null == wxOpenService) {
            throw new DataNotExistException("获取开放平台服务失败");
        }
        String configStoragekey = RedisKeyConstant.WX_OPEN_CONFIG_KEY.concat(componentAppId);
        WxOpenInRedisConfigStorage redisConfigStorage = (WxOpenInRedisConfigStorage)redisUtils.get(configStoragekey);
        String key = RedisKeyConstant.WX_OPEN_AUTH_KEY.concat(componentAppId).concat(":").concat(appId);
        Object objConfigStorage = redisUtils.get(key);
        if(ObjectUtils.isEmpty(objConfigStorage)) {
            OpenAuthDTO openAuthDTO = queryOpenAuthByComponentAppIdAndAppId(componentAppId, appId);
            if(openAuthDTO == null) throw new BusinessException("没有读取到开放平台配置权限!");
            OpenAuthOfExtend openAuthOfExtend = openAuthDTO.getOpenAuthOfExtend();
            if(openAuthOfExtend!=null) {
                OpenAuthOfWxOpen openAuthOfWxOpen = openAuthOfExtend.getOpenAuthOfWxOpen();
                if (openAuthOfWxOpen != null) {
                    redisConfigStorage.updateAuthorizerRefreshToken(appId, openAuthOfWxOpen.getAuthorizerRefreshToken());
                    WxOpenAuthorizerAccessToken authorizerAccessToken = new WxOpenAuthorizerAccessToken();
                    authorizerAccessToken.setAuthorizerRefreshToken(openAuthOfWxOpen.getAuthorizerRefreshToken());
                    authorizerAccessToken.setAuthorizerAccessToken(openAuthOfWxOpen.getAuthorizerAccessToken());
                    redisConfigStorage.updateAuthorizerAccessToken(appId, authorizerAccessToken);
                }
            }
        }else{
            redisConfigStorage = (WxOpenInRedisConfigStorage) objConfigStorage;
        }
        wxOpenService.setWxOpenConfigStorage(redisConfigStorage);
        WxOpenComponentService wxOpenComponentService = wxOpenService.getWxOpenComponentService();
        WxOpenMpService wxOpenMpService = wxOpenComponentService.getWxMpServiceByAppid(appId);
        if (null == wxOpenMpService) {
            throw new DataNotExistException("获取小程序服务WxMaService失败");
        }
        return wxOpenMpService;
    }
    /**
     * 获取小程序服务并将注册为bean
     *
     * @param appId
     * @return
     */
    @Override
    public WxOpenMaService getWxOpenMaService(String componentAppId, String appId) {
        WxOpenService wxOpenService = getBean().getWxOpenService(componentAppId);
        if (null == wxOpenService) {
            throw new DataNotExistException("获取开放平台服务失败");
        }
        String configStoragekey = RedisKeyConstant.WX_OPEN_CONFIG_KEY.concat(componentAppId);
        WxOpenInRedisConfigStorage redisConfigStorage = (WxOpenInRedisConfigStorage)redisUtils.get(configStoragekey);
        String key = RedisKeyConstant.WX_OPEN_AUTH_KEY.concat(componentAppId).concat(":").concat(appId);
        Object objConfigStorage = redisUtils.get(key);
        if(ObjectUtils.isEmpty(objConfigStorage)) {
            OpenAuthDTO openAuthDTO = queryOpenAuthByComponentAppIdAndAppId(componentAppId, appId);
            if(openAuthDTO == null) throw new BusinessException("没有读取到开放平台配置权限!");
            OpenAuthOfExtend openAuthOfExtend = openAuthDTO.getOpenAuthOfExtend();
            if(openAuthOfExtend!=null) {
                OpenAuthOfWxOpen openAuthOfWxOpen = openAuthOfExtend.getOpenAuthOfWxOpen();
                if (openAuthOfWxOpen != null) {
                    redisConfigStorage.updateAuthorizerRefreshToken(appId, openAuthOfWxOpen.getAuthorizerRefreshToken());
                    WxOpenAuthorizerAccessToken authorizerAccessToken = new WxOpenAuthorizerAccessToken();
                    authorizerAccessToken.setAuthorizerRefreshToken(openAuthOfWxOpen.getAuthorizerRefreshToken());
                    authorizerAccessToken.setAuthorizerAccessToken(openAuthOfWxOpen.getAuthorizerAccessToken());
                    redisConfigStorage.updateAuthorizerAccessToken(appId, authorizerAccessToken);
                }
            }
        }else{
            redisConfigStorage = (WxOpenInRedisConfigStorage) objConfigStorage;
        }
        wxOpenService.setWxOpenConfigStorage(redisConfigStorage);
        WxOpenComponentService wxOpenComponentService = wxOpenService.getWxOpenComponentService();
        WxOpenMaService wxOpenMaService = wxOpenComponentService.getWxMaServiceByAppid(appId);
        if (null == wxOpenMaService) {
            throw new DataNotExistException("获取小程序服务WxMaService失败");
        }
        return wxOpenMaService;

    }
    /**
     * 获取开放平台服务并将注册为bean
     *
     * @param
     * @return
     */
    @Override
    public WxCpService getDefaultWxCpService() {
        WxCpService wxCpService = SpringBeanUtil.getBean(WxCpService.class);
        if (wxCpService == null)  throw new BusinessException("get WxCpService service error!");
        return wxCpService;
    }

    @Override
    public WxCpTpService getDefaultWxCpTpService() {
        try {
            Integer configType = OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode();
            Integer configSubType = WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_TP.getCode();
            WxCpTpService wxCpTpService = SpringBeanUtil.getBean(WxCpTpService.class);
            if (wxCpTpService == null) throw new BusinessException("get WxCpTPService service error!");
            WxCpTpConfigStorage configStorage =wxCpTpService.getWxCpTpConfigStorage();
            String openConfigKey = "wx:cp:tp:t".concat(configType.toString()).concat(":s").concat(configSubType.toString());
            OpenConfigDTO openConfigDTO = null;
            Object openConfigObj = redisUtils.get(openConfigKey);
            if (ObjectUtils.isEmpty(openConfigObj)) {
                openConfigDTO = queryOpenConfig(configType, configSubType);
                if (openConfigDTO == null) throw new BusinessException("没有企微开放平台参数配置信息！");
                redisUtils.set(openConfigKey, openConfigDTO, 1000);
            } else {
                openConfigDTO = (OpenConfigDTO) openConfigObj;
            }
            OpenConfigOfExtend openConfigOfExtend = openConfigDTO!=null?openConfigDTO.getOpenConfigOfExtend():null;
            OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend != null ?openConfigOfExtend.getOpenConfigOfWxCp():null;
            JedisWxRedisOps wxRedisOps = new JedisWxRedisOps(redisProperties.getJedisPool());
            String suiteId = openConfigDTO.getComponentAppId();
            WxCpTpRedissonConfigImpl.WxCpTpRedissonConfigImplBuilder configStorageBuider = WxCpTpRedissonConfigImpl.builder().wxRedisOps(wxRedisOps);
            if(StringUtils.isNotEmpty(openConfigKey))configStorageBuider.keyPrefix(openConfigKey);
            if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppId()))configStorageBuider.corpId(openConfigDTO.getOpenAppId());
            if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppSecret()))configStorageBuider.corpSecret(openConfigDTO.getOpenAppSecret());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentAppId()))configStorageBuider.suiteId(suiteId);
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentSecret()))configStorageBuider.suiteSecret(openConfigDTO.getComponentSecret());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgToken()))configStorageBuider.token(openConfigDTO.getComponentMsgToken());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgAesKey()))configStorageBuider.aesKey(openConfigDTO.getComponentMsgAesKey());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyHost()))configStorageBuider.httpProxyHost(openConfigDTO.getHttpProxyHost());
            if(null!=openConfigDTO.getHttpProxyPort())configStorageBuider.httpProxyPort(openConfigDTO.getHttpProxyPort());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyUsername()))configStorageBuider.httpProxyUsername(openConfigDTO.getHttpProxyUsername());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyPassword()))configStorageBuider.httpProxyPassword(openConfigDTO.getHttpProxyPassword());

            configStorage = configStorageBuider.build();

            Object suiteTicket = redisUtils.get(RedisKeyConstant.WX_CP_TP_SUITE_TICKET.concat(suiteId));
            Object suiteAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_TP_SUITE_ACCESS_TOKEN.concat(suiteId));

            if(ObjectUtils.isNotEmpty(suiteTicket)){
                configStorage.updateSuiteTicket(suiteTicket.toString(), 1200);
            }
            if(ObjectUtils.isNotEmpty(suiteAccessTokenObj)) {
                WxAccessToken suiteAccessTokenEntity = (WxAccessToken)suiteAccessTokenObj;
                if(StringUtils.isNotEmpty(suiteAccessTokenEntity.getAccessToken())) {
                    configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
                }else{
                    suiteAccessTokenEntity.setAccessToken(openConfigOfWxCp.getComponentAccessToken());
                    suiteAccessTokenEntity.setExpiresIn(7200);
                    configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
                }
            }
            wxCpTpService.setWxCpTpConfigStorage(configStorage);
            return wxCpTpService;
        }catch(Exception ex){
            throw new BusinessException(ex.toString());
        }
    }

    @Override
    public WxCpTpService getAuthedWxCpTpService(Long tenantId, Integer configType, Integer configSubType, Integer appType) {
            WxCpTpService wxCpTpService = this.getBean().getDefaultWxCpTpService();
            WxCpTpConfigStorage wxCpTpConfigStorage = wxCpTpService.getWxCpTpConfigStorage();
            if(wxCpTpConfigStorage != null){
                OpenAuthDTO wxOpenAuthDTO = queryOpenAuthByTenantIdAndType(tenantId, appType);
                if(wxOpenAuthDTO != null){
                    OpenAuthOfExtend openAuthOfExtend = wxOpenAuthDTO.getOpenAuthOfExtend();
                    if(openAuthOfExtend!=null) {
                        if(appType == WxCpServiceTypeConstant.CP_TYPE_TP) {
                            OpenAuthOfWxCpTp openAuthOfWxCpTp = openAuthOfExtend.getOpenAuthOfWxCpTp();
                            wxCpTpConfigStorage.updateSuiteTicket(openAuthOfWxCpTp.getSuiteTicket(),1200);
                            wxCpTpConfigStorage.updateSuiteAccessToken(openAuthOfWxCpTp.getSuiteAccessToken(),7200);
                            wxCpTpConfigStorage.updateAccessToken(wxOpenAuthDTO.getAppId(),openAuthOfWxCpTp.getCorpAccessToken(),7200);
                        }
                    }
                }
                wxCpTpService.setWxCpTpConfigStorage(wxCpTpConfigStorage);
            }
            return wxCpTpService;
    }

    @Override
    public WxCpTpService getDefaultWxCpDkService() {
        try {
            Integer configType = OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode();
            Integer configSubType = WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_DK.getCode();
            WxCpTpService wxCpTpService = SpringBeanUtil.getBean(WxCpTpService.class);
            if (wxCpTpService == null) new WxCpTpServiceImpl();

            String openConfigKey = "wx:cp:dk:t".concat(configType.toString()).concat(":s").concat(configSubType.toString());
            OpenConfigDTO openConfigDTO = null;
            Object openConfigObj = redisUtils.get(openConfigKey);
            if (ObjectUtils.isEmpty(openConfigObj)) {
                openConfigDTO = queryOpenConfig(configType, configSubType);
                if (openConfigDTO == null) throw new BusinessException("没有企微开放平台参数配置信息！");
                redisUtils.set(openConfigKey, openConfigDTO, 1000);
            } else {
                openConfigDTO = (OpenConfigDTO) openConfigObj;
            }
            OpenConfigOfExtend openConfigOfExtend = openConfigDTO!=null?openConfigDTO.getOpenConfigOfExtend():null;
            OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend != null ?openConfigOfExtend.getOpenConfigOfWxCp():null;
            JedisWxRedisOps wxRedisOps = new JedisWxRedisOps(redisProperties.getJedisPool());
            String suiteId = openConfigDTO.getComponentAppId();
            WxCpTpRedissonConfigImpl.WxCpTpRedissonConfigImplBuilder configStorageBuider = WxCpTpRedissonConfigImpl.builder().wxRedisOps(wxRedisOps);
            if(StringUtils.isNotEmpty(openConfigKey))configStorageBuider.keyPrefix(openConfigKey);
            if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppId()))configStorageBuider.corpId(openConfigDTO.getOpenAppId());
            if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppSecret()))configStorageBuider.corpSecret(openConfigDTO.getOpenAppSecret());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentAppId()))configStorageBuider.suiteId(suiteId);
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentSecret()))configStorageBuider.suiteSecret(openConfigDTO.getComponentSecret());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgToken()))configStorageBuider.token(openConfigDTO.getComponentMsgToken());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgAesKey()))configStorageBuider.aesKey(openConfigDTO.getComponentMsgAesKey());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyHost()))configStorageBuider.httpProxyHost(openConfigDTO.getHttpProxyHost());
            if(null!=openConfigDTO.getHttpProxyPort())configStorageBuider.httpProxyPort(openConfigDTO.getHttpProxyPort());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyUsername()))configStorageBuider.httpProxyUsername(openConfigDTO.getHttpProxyUsername());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyPassword()))configStorageBuider.httpProxyPassword(openConfigDTO.getHttpProxyPassword());

            OpenConfigOfWxCpProvider wxCpProvider = openConfigOfWxCp!=null?openConfigOfWxCp.getWxCpProvider():null;
            String providerSecret = wxCpProvider!=null?wxCpProvider.getProviderSecret():null;
            if(StringUtils.isNotEmpty(providerSecret))configStorageBuider.providerSecret(providerSecret);

            WxCpTpConfigStorage configStorage = configStorageBuider.build();

            String suiteTicket = redisUtils.getString(RedisKeyConstant.WX_CP_DK_SUITE_TICKET.concat(suiteId));
            Object suiteAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_DK_SUITE_ACCESS_TOKEN.concat(suiteId));

            if(StringUtils.isNotEmpty(suiteTicket)){
                configStorage.updateSuiteTicket(suiteTicket, 1200);
            }
            if(ObjectUtils.isNotEmpty(suiteAccessTokenObj)) {
                 WxAccessToken suiteAccessTokenEntity = (WxAccessToken)suiteAccessTokenObj;
                if(StringUtils.isNotEmpty(suiteAccessTokenEntity.getAccessToken())) {
                    configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
                }else{
                    suiteAccessTokenEntity.setAccessToken(openConfigOfWxCp.getComponentAccessToken());
                    suiteAccessTokenEntity.setExpiresIn(7200);
                    configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
                }
            }
            wxCpTpService.setWxCpTpConfigStorage(configStorage);
            return wxCpTpService;
        }catch(Exception ex){
            throw new BusinessException(ex.toString());
        }
    }

    @Override
    public WxCpTpService getDefaultWxCpContactService() {
        try {
            Integer configType = OpenApiConfigEnum.OPEN_CONFIG_TYPE_WECHAT_CP.getCode();
            Integer configSubType = WxCpAppTypeEnum.WECHAT_CP_APP_TYPE_CONTACT.getCode();
            WxCpTpService wxCpTpService = SpringBeanUtil.getBean(WxCpTpService.class);
            if (wxCpTpService == null) new WxCpTpServiceImpl();

            String openConfigKey = "wx:cp:contact:t".concat(configType.toString()).concat(":s").concat(configSubType.toString());
            OpenConfigDTO openConfigDTO = null;
            Object openConfigObj = redisUtils.get(openConfigKey);
            if (ObjectUtils.isEmpty(openConfigObj)) {
                openConfigDTO = queryOpenConfig(configType, configSubType);
                if (openConfigDTO == null) throw new BusinessException("没有企微开放平台参数配置信息！");
                redisUtils.set(openConfigKey, openConfigDTO, 1000);
            } else {
                openConfigDTO = (OpenConfigDTO) openConfigObj;
            }
            OpenConfigOfExtend openConfigOfExtend = openConfigDTO!=null?openConfigDTO.getOpenConfigOfExtend():null;
            OpenConfigOfWxCp openConfigOfWxCp = openConfigOfExtend != null ?openConfigOfExtend.getOpenConfigOfWxCp():null;
            JedisWxRedisOps wxRedisOps = new JedisWxRedisOps(redisProperties.getJedisPool());
            String suiteId = openConfigDTO.getComponentAppId();
            WxCpTpRedissonConfigImpl.WxCpTpRedissonConfigImplBuilder configStorageBuider = WxCpTpRedissonConfigImpl.builder().wxRedisOps(wxRedisOps);
            if(StringUtils.isNotEmpty(openConfigKey))configStorageBuider.keyPrefix(openConfigKey);
            if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppId()))configStorageBuider.corpId(openConfigDTO.getOpenAppId());
            if(StringUtils.isNotEmpty(openConfigDTO.getOpenAppSecret()))configStorageBuider.corpSecret(openConfigDTO.getOpenAppSecret());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentAppId()))configStorageBuider.suiteId(suiteId);
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentSecret()))configStorageBuider.suiteSecret(openConfigDTO.getComponentSecret());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgToken()))configStorageBuider.token(openConfigDTO.getComponentMsgToken());
            if(StringUtils.isNotEmpty(openConfigDTO.getComponentMsgAesKey()))configStorageBuider.aesKey(openConfigDTO.getComponentMsgAesKey());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyHost()))configStorageBuider.httpProxyHost(openConfigDTO.getHttpProxyHost());
            if(null!=openConfigDTO.getHttpProxyPort())configStorageBuider.httpProxyPort(openConfigDTO.getHttpProxyPort());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyUsername()))configStorageBuider.httpProxyUsername(openConfigDTO.getHttpProxyUsername());
            if(StringUtils.isNotEmpty(openConfigDTO.getHttpProxyPassword()))configStorageBuider.httpProxyPassword(openConfigDTO.getHttpProxyPassword());

            WxCpTpConfigStorage configStorage = configStorageBuider.build();

            String suiteTicket = redisUtils.getString(RedisKeyConstant.WX_CP_CONTACT_SUITE_TICKET + suiteId);
            Object suiteAccessTokenObj = redisUtils.get(RedisKeyConstant.WX_CP_CONTACT_SUITE_ACCESS_TOKEN + suiteId);

            if(StringUtils.isNotEmpty(suiteTicket)){
                configStorage.updateSuiteTicket(suiteTicket, 1200);
            }
            if(ObjectUtils.isNotEmpty(suiteAccessTokenObj)) {
                WxAccessToken suiteAccessTokenEntity = (WxAccessToken)suiteAccessTokenObj;
                if(StringUtils.isNotEmpty(suiteAccessTokenEntity.getAccessToken())) {
                    configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
                }else{
                    suiteAccessTokenEntity.setAccessToken(openConfigOfWxCp.getComponentAccessToken());
                    suiteAccessTokenEntity.setExpiresIn(7200);
                    configStorage.updateSuiteAccessToken(suiteAccessTokenEntity);
                }
            }
            wxCpTpService.setWxCpTpConfigStorage(configStorage);
            return wxCpTpService;
        }catch(Exception ex){
            throw new BusinessException(ex.toString());
        }
    }

    @Override
    public DingTalkService getDefaultDingTalkService() {
        DingTalkService dingTalkService = SpringBeanUtil.getBean(DingTalkService.class);
        if (dingTalkService == null)  throw new BusinessException("get DingTalkService service error!");
        return dingTalkService;
    }
    private OpenServiceImpl getBean() {
        return SpringBeanUtil.getBean(this.getClass());
    }
}
